//
//  ImageListViewController.m
//  CheXunWang
//
//  Created by zhu lin on 12/20/11.
//  Copyright 2011 Zhulin. All rights reserved.
//

#import "ImageListViewController.h"
#import "ZLImageItem.h"
#import "CustomBarButtonItem.h"
#import "HttpServices.h"
#import "PhotoBrowser.h"

#define kPageSize				15
#define kBaseImageTag			2000
#define kCustomCellHeight		83.0
#define kCustomBlankCellHeight	416.0

#define kImageListKey		@"list"
#define kImagePathKey		@"imagePath"
#define kBigImagePathKey	@"bigImagePath"

/*
 {
 "year":null,
 "seriesId":2102,
 "imagePath":"http://img01.chexun.com/images/auto/aodi/q5/2011k20tsijsx/240180/201122220231731906042.jpg",
 "albumId":3194,
 "modelId":null,
 "bigImagePath":"http://img01.chexun.com/images/auto/aodi/q5/2011k20tsijsx/400300/201122220231731906042.jpg",
 "photoId":"194413"
 }
 */

@interface ImageListViewController()
@property (nonatomic, retain) ATMHud *hud;
@property (nonatomic, assign) NSInteger lastPageIndex;
@property (nonatomic, retain) NSMutableArray *imageInfoArray;
@property (nonatomic, retain) ASIHTTPRequest *imagelistRequest;
@property (nonatomic, retain) NSMutableDictionary	*loadedImages;
@property (nonatomic, retain) NSMutableDictionary *imageDownloadsInProgress;

- (void)loadImages;
- (UIImage *)loadImageOfIndex:(int)index;
@end

@implementation ImageListViewController
@synthesize hud;
@synthesize seriesID, modelID, lastPageIndex;
@synthesize imageInfoArray;
@synthesize loadedImages;
@synthesize imagelistRequest, imageDownloadsInProgress;

- (ATMHud *)hud
{
	if (hud == nil) {
		hud = [[ATMHud alloc] init];
		[self.view addSubview:hud.view];
	}
	return hud;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	//self.title = @"图 片";
	self.navigationItem.hidesBackButton = YES;
	CustomBarButtonItem *backButton = [[CustomBarButtonItem alloc] initWithTitle:@"返 回" style:LeftBarButtonItemBackStyle target:self action:@selector(popViewController:)];
	self.navigationItem.leftBarButtonItem = backButton;
	[backButton release];
	
	self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //self.tableView.rowHeight = 83.0;//seen from apple sample code
	self.tableView.tableHeaderView.frame = CGRectMake(0.0, 0.0, 320.0, 12.0);
	
	UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
	moreButton.frame = CGRectMake(0.0F, 0.0, 320.0, 35.0);
	[moreButton setTitle:@"载入更多..." forState:UIControlStateNormal];
	[moreButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
	[moreButton addTarget:self action:@selector(loadImages) forControlEvents:UIControlEventTouchUpInside];
	self.tableView.tableFooterView = moreButton;
	
	
	self.imageInfoArray = [NSMutableArray array];
	self.loadedImages = [NSMutableDictionary dictionary];
	self.imageDownloadsInProgress = [NSMutableDictionary dictionary];
	self.lastPageIndex = 0;
	[self loadImages];
}

#pragma mark -
#pragma mark memory manage
- (void)viewDidDisappear:(BOOL)animated
{
	for(ASIHTTPRequest *request in [self.imageDownloadsInProgress allValues])
	{
		if (request != nil) {
			[request clearDelegatesAndCancel];
		}
	}
	[self.imagelistRequest clearDelegatesAndCancel];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
	[self.loadedImages removeAllObjects];
	for(ASIHTTPRequest *request in self.imageDownloadsInProgress)
	{
		if (request != nil) {
			[request clearDelegatesAndCancel];
		}
	}
	[self.imagelistRequest clearDelegatesAndCancel];
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
	self.hud = nil;
	
	self.imageInfoArray = nil;
	self.loadedImages = nil;
	self.imageDownloadsInProgress = nil;
	self.imagelistRequest = nil;
}

- (void)dealloc {
    [super dealloc];
	
	[hud release];
	[imageInfoArray release];
	[loadedImages release];
	[imageDownloadsInProgress release];
	[imagelistRequest release];
}

#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if ([self.imageInfoArray count] == 0) {
		return 1;
	}
	
	return (([self.imageInfoArray count]+1)/3);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if ([self.imageInfoArray count] == 0) {
		return kCustomBlankCellHeight;
	}
	
	return kCustomCellHeight;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *blankCellIdentifier = @"blankCell";
	static NSString *imageCellIdentifier = @"imageCell";
    
	if ([self.imageInfoArray count] == 0) {
		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:blankCellIdentifier];
        if (cell == nil)
		{
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
										   reuseIdentifier:blankCellIdentifier] autorelease];
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
		return cell;
	}
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:imageCellIdentifier];
    if (cell == nil)
	{
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:imageCellIdentifier];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		
		for (int i = 0; i<3; i++) {
			ZLImageItem *imageItem = [[ZLImageItem alloc] initWithFrame:CGRectMake(5.0*(i+1) + 100.0*i, 4.0, 100.0, 75.0) andDelegate:self];
			imageItem.tag = i+ kBaseImageTag;
			[cell.contentView addSubview:imageItem];
			[imageItem release];
		}
	}
    
    // Configure the cell...
	for (int i= 0; i<3; i++) {
		ZLImageItem *imageItem = (ZLImageItem *)[cell.contentView viewWithTag:(i + kBaseImageTag)];
		int index = i + indexPath.row*3;
		if (index >= [self.imageInfoArray count]) {
			imageItem.hidden = YES;
			continue;
		}
		
		imageItem.index = index + 1;
		
		// load image
		imageItem.imageItemView.image = [self loadImageOfIndex:index];
	}
	
    return cell;
}

#pragma mark -
#pragma mark image download methods
- (UIImage *)loadImageOfIndex:(int)index
{
	NSString *key = [NSString stringWithFormat:@"%d", index];
	UIImage *image = [self.loadedImages valueForKey:key];
	if (image) {
		return image;
	}
	
	NSDictionary *dic = (NSDictionary *)[self.imageInfoArray objectAtIndex:index];
	NSString *imageURL = (NSString *)[dic valueForKey:kImagePathKey];
	
	ASIHTTPRequest *request = [self.imageDownloadsInProgress objectForKey:key];
	if (request == nil) {
		request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:imageURL]];
		[request setDelegate:self];
		//[request setDownloadDestinationPath:imagePath];
		[request startAsynchronous];
		[self.imageDownloadsInProgress setObject:request forKey:key];
	}
	
	return [UIImage imageNamed:@"ios_common_list_item_avatar.png"];
}

#pragma mark -
#pragma mark ASIHTTPRequestDelegate methods
- (void)requestFinished:(ASIHTTPRequest *)request
{
	NSArray *imageRequestArray = [self.imageDownloadsInProgress allKeysForObject:request];
	if (imageRequestArray == nil || [imageRequestArray count] == 0) {
		if (self.lastPageIndex == 1) {
			[self.hud hide];
		}
		
		NSData *responseData = [request responseData];
		NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
		
		/*
		 [
		 {"total":521,"pagesize":10,"pageCount":53,"pagekeys":2,
		 "list":[{"year":null,"seriesId":2102,"imagePath":"http://img01.chexun.com/images/auto/aodi/q5/2011k20tsijsx/240180/201122220231731906042.jpg","albumId":3194,"modelId":null,"bigImagePath":"http://img01.chexun.com/images/auto/aodi/q5/2011k20tsijsx/400300/201122220231731906042.jpg","photoId":"194413"}]
		 }
		 ]
		 */
		NSDictionary *allInfo = (NSDictionary *)[(NSArray *)[result JSONValue] objectAtIndex:0];
		if (!allInfo) {
			return;
		}
		NSArray *tmpImageArray = (NSArray *)[allInfo valueForKey:kImageListKey];
		[self.imageInfoArray addObjectsFromArray:tmpImageArray];
		
		if ([tmpImageArray count] < kPageSize) {
			self.tableView.tableFooterView = nil;
		}
		
		[self.tableView reloadData];
	} else {
		// loadimage request
		UIImage * image = [UIImage imageWithData:[request responseData]];
		if (image) {
			NSString *index = (NSString *)[imageRequestArray objectAtIndex:0];
			[self.imageDownloadsInProgress removeObjectForKey:index];
			[self.loadedImages setObject:image forKey:index];
			
			int row = [index intValue]/3;
			int cellIndex = [index intValue]%3;
			UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
			ZLImageItem *imageItem = (ZLImageItem *)[cell viewWithTag:(cellIndex + kBaseImageTag)];
			imageItem.imageItemView.image = image;
		}
	}	
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
	NSArray *imageRequestArray = [self.imageDownloadsInProgress allKeysForObject:request];
	if (imageRequestArray == nil || [imageRequestArray count] == 0) {
		[self.hud setAccessoryPosition:ATMHudAccessoryPositionLeft];
		[self.hud setCaption:@"访问出错！"];
		[self.hud setImage:[UIImage imageNamed:@"11-x"]];
		[self.hud setActivity:NO];
		[self.hud update];
		[self.hud hideAfter:1.0f];
	} else {
		// stop loadimage
		NSString *index = (NSString *)[imageRequestArray objectAtIndex:0];
		[self.imageDownloadsInProgress removeObjectForKey:index];
	}
}

#pragma mark -
#pragma mark actions
- (void)loadImages
{
	if (self.seriesID || self.modelID) {
		self.lastPageIndex++;
		
		self.imagelistRequest = [HttpServices getPhotoListBySeriesId:self.seriesID 
									 modelId:self.modelID 
									pagekeys:[NSString stringWithFormat:@"%d", self.lastPageIndex] 
									pagesize:[NSString stringWithFormat:@"%d", kPageSize] 
								 andDelegate:self];
		if (self.lastPageIndex == 1) {
			// show hud
			[self.hud setAccessoryPosition:ATMHudAccessoryPositionLeft];
			[self.hud setCaption:@"正在载入"];
			[self.hud setActivity:YES];
			[self.hud show];
		}
	}
}

- (void)showLargePicture:(int)index
{
	// Browser
	NSMutableArray *photos = [[NSMutableArray alloc] init];
	for (int i = 0; i < [self.imageInfoArray count]; i++) {
		NSDictionary *dic = (NSDictionary *)[self.imageInfoArray objectAtIndex:i];
		NSString *largeImageURL = (NSString *)[dic valueForKey:kBigImagePathKey];
		[photos addObject:[Photo photoWithURL:[NSURL URLWithString:largeImageURL]]];
	}
	
	// Create browser
	PhotoBrowser *browser = [[PhotoBrowser alloc] initWithPhotos:photos];
	[browser setInitialPageIndex:(index - 1)]; 
	[self.navigationController pushViewController:browser animated:YES];
	[browser release];
	[photos release];	
}

- (void)popViewController:(id)sender
{	
	[self.navigationController popViewControllerAnimated:YES];
}

@end
